﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    internal class TInventoryAlertRepository : BaseRepository<TMaterial>, ITInventoryAlertRepository
    {
        public TInventoryAlertRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 库存预警查询
        /// </summary>
        /// <param name="totalCount"></param>
        /// <param name="WarningType"></param>
        /// <param name="warehouse"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<InventoryWarnModel> GetInventoryWarnPagingList(out int totalCount, int? WarningType, int? warehouse, int pageIndex, int pageSize)
        {
            totalCount = 0;


            var list = Context.TInventories.AsQueryable();

            if(WarningType!=null)
            {
                list = list.Where(x => x.InventoryAlert == WarningType);
            }
            if(warehouse.HasValue)
            {
                list = list.Where(x => x.WarehouseId == warehouse);
            }

            totalCount = list.Count();

            var materialIds = list.Select(x => x.MaterialId).ToList();
            var materialList = Context.TMaterial.Where(m => materialIds.Contains(m.Id)).ToList();

            var items = list.OrderBy(x => x.InventoryAlert)
         .Skip((pageIndex - 1) * pageSize)
         .Take(pageSize)
         .ToList()
         .Select(x =>
         {
          var material = materialList.FirstOrDefault(m => m.Id == x.MaterialId);

          return new InventoryWarnModel
                    {
                        MaterialId = x.MaterialId,
                        MaterialCode = x.MaterialCode,
                        MaterialName = x.MaterialName,
                        MaterialTypeName = x.MaterialTypeName,
                        WarnType = x.InventoryAlert,
                        QTY = x.AvailableQty,
                        WhId = x.WarehouseId,
                        WhName = x.WarehouseName,
                        MinSafetyStock = material?.MinSafetyStock ?? 0,
                        MaxSafetyStock = material?.MaxSafetyStock ?? 0,
                    };
                }).ToList();

            return items;
        }


        /// <summary>
        /// 封装方法
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private TMaterial? GetOneMaterial(int? id)
        {
            return Context.TMaterial.AsQueryable().FirstOrDefault(s => s.Id == id);

        }
    }
}
